﻿/*
 * Created by SharpDevelop.
 * User: Administrator
 * Date: 3/1/2011
 * Time: 8:30 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using TomatoSynchronizer.Entities;
using TomatoSynchronizer.Store;
using HtmlAgilityPack;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace TomatoSynchronizer.Synchronizer
{
	/// <summary>
	/// Description of SlideImageSynchronizer
	/// </summary>
	public static class SlideImageSynchronizer
	{
		public static void Synchronize(Site siteSrc,Site siteDest,HtmlWeb client,SyncDirection direction)
		{
			switch(direction)
			{
				case SyncDirection.Download:
					UpLoadItems(siteDest,siteSrc,client,direction);
					break;
				case SyncDirection.Upload:
					UpLoadItems(siteSrc,siteDest,client,direction);
					break;
				case SyncDirection.DownloadAndUpload:
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					break;
				case SyncDirection.UploadAndDownload:
					UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					UpLoadItems(siteDest,siteSrc,client,SyncDirection.Download);
					break;
				case SyncDirection.Synchronize:
					MappingStore mappingSrc = UpLoadItems(siteSrc,siteDest,client,SyncDirection.Upload);
					
					SlideImageStore SlideImageStoreDest = new SlideImageStore(siteDest,client);
					var slide_images = SlideImageStoreDest.DownloadItems();
					
					foreach(SlideImage slide_image in slide_images)
					{
						bool sync = false;
						
						foreach(Mapping mapping in mappingSrc.Mappings)
						{
							if(mapping.DestValue == slide_image.image_id)
							{
								sync = true;
							}
						}
						
						if(!sync)
						{
							if(!SlideImageStoreDest.DeleteItem(slide_image.image_id))
							{
								throw new Exception("Could not delete the SlideImage " + slide_image.image_id + " in site " + siteDest.Name);
							}
						}
					}
					break;
			}
		}
		
		private static MappingStore UpLoadItems(Site _siteSrc,Site _siteDest,HtmlWeb client,SyncDirection direction)
		{
			SlideImageStore SlideImageStoreSrc = new SlideImageStore(_siteSrc,client);
			SlideImageStore SlideImageStoreDest = new SlideImageStore(_siteDest,client);
			
			SlideImage[] SlideImagesSrc =  SlideImageStoreSrc.LoadItems();
			SlideImage[] SlideImagesDest =  SlideImageStoreDest.LoadItems();
			
			MappingStore mappingStoreSrc = new MappingStore(_siteSrc,_siteDest,"image_id");
			MappingStore mappingStoreDest = new MappingStore(_siteDest,_siteSrc,"image_id");
			
			mappingStoreSrc.Clean<SlideImage>(SlideImageStoreSrc,SlideImageStoreDest);
			mappingStoreDest.Clean<SlideImage>(SlideImageStoreDest,SlideImageStoreSrc);
			
			MappingStore mappingStore = new MappingStore(_siteSrc,_siteDest,"languages_id");
			
			List<SlideImage> alreadySynchronized = new List<SlideImage>();
			
			foreach(SlideImage SlideImageSrc in SlideImagesSrc)
			{
				//we assume the SlideImage is not yet synchronized
				bool synchronized = false;
				
				//we check if a mapping already exists for this SlideImage in the destination store
				foreach(Mapping mapping in mappingStoreSrc.Mappings)
				{
					if(mapping.SrcValue == SlideImageSrc.image_id && synchronized == false)
					{
						if(!string.IsNullOrEmpty(mapping.DestValue))
						{
							//this SlideImage already exists in the destination store
							//we check if everything changed since the last synchronization
							SlideImage SlideImageDest = SlideImageStoreDest.GetItem(mapping.DestValue);
							if(!string.IsNullOrEmpty(SlideImageDest.image_id))
							{
								synchronized = SynchronizeItem(SlideImageSrc,SlideImageDest);
							}
							else
							{
								//the mapping exists, but the SlideImage has been deleted in the destination store
								//we set a flag that this mapping does not exists anymore
								mapping.Exists = false;
							}
						}
					}
				}
				
				if(!synchronized)
				{
					//there is no mapping, we check if this SlideImage already exists in the destination store
					foreach(SlideImage SlideImageDest in SlideImagesDest)
					{
						foreach(Mapping mapping in mappingStore.Mappings)
						{
							try
							{
								if(SlideImageSrc.image_urls["image_url[" + mapping.SrcValue + "]"] == SlideImageDest.image_urls["image_urls[" + mapping.DestValue + "]"] && synchronized == false && !alreadySynchronized.Contains(SlideImageSrc))
								{
									//we get the 2 currencies from sites to get sure they really exist
									SlideImage src = SlideImageSrc.Store.GetItem(SlideImageSrc.image_id);
									SlideImage dest = SlideImageDest.Store.GetItem(SlideImageDest.image_id);
									
									if(!string.IsNullOrEmpty(src.image_id))
									{
										if(!string.IsNullOrEmpty(dest.image_id))
										{
											Mapping _mapping = new Mapping(SlideImageSrc.image_id,SlideImageDest.image_id,"image_id");
											mappingStoreSrc.Mappings.Add(_mapping);
											
											synchronized = SynchronizeItem(SlideImageSrc,SlideImageDest);
										}
										else
										{
											synchronized = false;
										}
									}
									else
									{
										synchronized = true;
									}
								}
							}
							catch (KeyNotFoundException)
							{
								
							}
						}
						
					}
				}
				
				if(!synchronized)
				{
					//no mapping the SlideImage is new
					//we insert it in the destination store
					string remoteId = string.Empty;																																		
					
					Dictionary<string, string> _descriptions = new Dictionary<string, string>();
					Dictionary<string, string> _image_urls = new Dictionary<string, string>();
					Dictionary<string, string> _slide_images = new Dictionary<string, string>();
					
					MappingStore _mappingStore = new MappingStore(SlideImageSrc.Store.site,_siteDest,"languages_id");
					foreach(Mapping mapping in _mappingStore.Mappings)
					{
						_descriptions["description[" + mapping.DestValue + "]"] = SlideImageSrc.descriptions["description[" + mapping.SrcValue + "]"];
						_image_urls["image_url[" + mapping.DestValue + "]"] = SlideImageSrc.image_urls["image_url[" + mapping.SrcValue + "]"];
						_slide_images["image" + mapping.DestValue] = "sites/" + _siteSrc.Name + "/SlideImages/" + SlideImageSrc.image_id + "/" + SlideImageSrc.slide_images["slide_image" + mapping.SrcValue];
					}
					
					SlideImageSrc.descriptions = _descriptions;
					SlideImageSrc.image_urls = _image_urls;
					SlideImageSrc.slide_images = _slide_images;
					
					remoteId = SlideImageStoreDest.InsertItem(SlideImageSrc);
					
					synchronized = remoteId != string.Empty;
					
					if(!synchronized)
					{
						throw new Exception("The SlideImage " + SlideImageSrc.image_id + " has not been synchronized");
					}
					
					Mapping _mapping = new Mapping(SlideImageSrc.image_id,remoteId,"image_id");
					mappingStoreSrc.Mappings.Add(_mapping);
					synchronized = true;
				}
				
				if(!synchronized)
				{
					throw new Exception("could not synchronize the SlideImage " + SlideImageSrc.image_id);
				}
				
//				SlideImageStoreSrc.PersistItem(SlideImageSrc);
				alreadySynchronized.Add(SlideImageSrc);
			}
			
			mappingStoreSrc.Save();
			
			mappingStoreDest.Truncate();
			
			//we save the mappings in the destination MappingStore too
			foreach(Mapping mapping in mappingStoreSrc.Mappings)
			{
				if(mapping.Exists)
				{
					Mapping mappingDest = new Mapping(mapping.DestValue,mapping.SrcValue,mapping.Property);
					mappingStoreDest.Mappings.Add(mappingDest);
				}
			}
			
			mappingStoreDest.Save();
			
			//we check if the 2 MappingStore are synchronized
			if(mappingStoreSrc.Mappings.Count != mappingStoreDest.Mappings.Count)
			{
				throw new Exception("The mapping store for the SlideImages are not synchronized");
			}
			
			return mappingStoreSrc;
		}
		
		private static bool SynchronizeItem(SlideImage SlideImageSrc,SlideImage SlideImageDest)
		{
			bool synchronized = true;
			
			if(!SlideImageSrc.Equals(SlideImageDest))
			{
				synchronized = false;
				
				//we update the destination SlideImage
				SlideImageSrc.language_id = SlideImageDest.language_id;
				SlideImageSrc.image_id = SlideImageDest.image_id;
				
				var languages = SlideImageDest.Store.site.GetLanguageStore().LoadItems();
				
				Dictionary<string, string> _descriptions = new Dictionary<string, string>();
				Dictionary<string, string> _image_urls = new Dictionary<string, string>();
				Dictionary<string, string> _slide_images = new Dictionary<string, string>();
				
				MappingStore mappingStore = new MappingStore(SlideImageSrc.Store.site,SlideImageDest.Store.site,"languages_id");
				foreach(Mapping mapping in mappingStore.Mappings)
				{
					_descriptions["description[" + mapping.DestValue + "]"] = SlideImageSrc.descriptions["description[" + mapping.SrcValue + "]"];
					_image_urls["image_url[" + mapping.DestValue + "]"] = SlideImageSrc.image_urls["image_url[" + mapping.SrcValue + "]"];
					_slide_images["slide_image" + mapping.DestValue] = "sites/" + SlideImageSrc.Store.site.Name + "/SlideImages/" + SlideImageSrc.image_id + "/" + SlideImageSrc.slide_images["slide_image" + mapping.SrcValue];
				}
				
				SlideImageSrc.descriptions = _descriptions;
				SlideImageSrc.image_urls = _image_urls;
				SlideImageSrc.slide_images = _slide_images;
				
				synchronized = SlideImageDest.Store.UpdateItem(SlideImageSrc);
			}
			
			return synchronized;
		}
		
		private static string UploadItem(SlideImageStore SlideImageStoreDest,SlideImage SlideImage)
		{
			string remoteId = string.Empty;
			
			remoteId = SlideImageStoreDest.InsertItem(SlideImage);
			
			return remoteId;
		}
	}
}
